//
//  MagazineInfoViewController.m
//  JianChaRiBao
//
//  Created by yuzhou on 13-5-17.
//  Copyright (c) 2013年 wzyk. All rights reserved.
//

#import "MagazineInfoViewController.h"
#import "MagazineContentCell.h"
#import "UIImageView+WebCache.h"
#import <QuartzCore/QuartzCore.h>
#import "ArticleViewController.h"
#import "DataBase.h"
#import "ASIDownloadCache.h"
#import "MagazineHistoryViewController.h"
#import "ActivateViewController.h"
@interface MagazineInfoViewController ()
{
    ActivateViewController *accountViewCon;
}

@end

@implementation MagazineInfoViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        shouldSwipeBack = YES;
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(downloading:) name:KDownloading object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(downloadComplete:) name:KDownloadComplete object:nil];

    }
    return self;
}
-(void)downloading:(NSNotification *)notification{
    NSDictionary * dict = [notification object];
    NSString * idStr = [dict objectForKey:@"itemID"];
    if ([idStr isEqualToString: [_basicInfo objectForKey:@"magitemid"]]) {
        showLabel.text = [NSString stringWithFormat:@"正在下载:%@/%@",[dict objectForKey:@"count"],[dict objectForKey:@"arrayCount"]];
    }

}
-(void)downloadComplete:(NSNotification *)notification{

    NSDictionary * dict = [notification object];
    NSString * idStr = [dict objectForKey:@"itemID"];
    if ([idStr isEqualToString: [_basicInfo objectForKey:@"magitemid"]]) {
        showLabel.text = [NSString stringWithFormat:@"已完成:成功%@ 失败%@",[dict objectForKey:@"SucceseCount"],[dict objectForKey:@"failCount"]];
        downloadBtn.hidden = YES;
        downloadLabel.hidden = NO;

    }
  
}
- (IBAction)downloadBtnClicked:(id)sender {
    if ([ActivateManager shareManager].isActivated) {
        NSMutableArray * array = [NSMutableArray arrayWithCapacity:0];
        for (NSDictionary * dict in _contentArray) {
            if ([[dict objectForKey:@"is_view"]intValue] == 1) {
                [array addObject:dict];
            }
        }
        if (array.count < _contentArray.count) {
            ABPromptView * abp = [[[ABPromptView alloc]initWithTitle:[NSString stringWithFormat:@"您只能下载%d篇杂志",array.count]]autorelease];
            [abp show];
        }
        [[DownloadArticle shareDownloadArticle]downloadMagaWithArray:array dict:_detailInfo];
        showLabel.hidden = NO;
        showLabel.text = @"正在下载...";
        downloadBtn.hidden = YES;
    }else{
        ABPromptView * abp = [[[ABPromptView alloc]initWithTitle:[NSString stringWithFormat:@"您尚未激活"]]autorelease];
        [abp show];
    }
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    downloadBtn.hidden = YES;
    downloadLabel.hidden = YES;
    showLabel.hidden = YES;
    if (self.pushFromHistory) {
        historyButton.hidden = YES;
        historyImage.hidden = YES;
    }

    contentTableView.contentInset = UIEdgeInsetsMake(0, 0, 16, 0);
    contentTableView.tableHeaderView = headerView;
    [self getData];
    
    coverImageView.layer.shadowColor = [UIColor blackColor].CGColor;
    coverImageView.layer.shadowOpacity = 0.45;
    coverImageView.layer.shadowOffset = CGSizeMake(0, 3);
    coverImageView.layer.shadowPath = [UIBezierPath bezierPathWithRect:coverImageView.bounds].CGPath;
    coverImageView.layer.masksToBounds = NO;
    
    //遮盖试图点击事件
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideMenu)];
    [maskView addGestureRecognizer:tapGesture];
    [tapGesture release];
    
    UISwipeGestureRecognizer *swipeGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(hideMenu)];
    swipeGesture.direction = UISwipeGestureRecognizerDirectionRight | UISwipeGestureRecognizerDirectionLeft;
    [maskView addGestureRecognizer:swipeGesture];
    [swipeGesture release];
    
    //阴影效果
    MainView.layer.shadowColor = [UIColor blackColor].CGColor;
    MainView.layer.shadowOpacity = 0.45;
    MainView.layer.shadowOffset = CGSizeMake(0, 6);
    MainView.layer.shadowPath = [UIBezierPath bezierPathWithRect:CGRectMake(0, 0, 320, 548)].CGPath;
    MainView.layer.masksToBounds = NO;
    
    accountViewCon = [[ActivateViewController alloc]initWithNibName:@"ActivateViewController" bundle:nil];
    [ActiveView addSubview:accountViewCon.view];

    
}
- (void)hideMenu
{
    [UIView animateWithDuration:0.3 animations:^{
        CGRect rect = MainView.frame;
        rect.origin.x = 0;
        MainView.frame = rect;
        maskView.alpha = 0;
    }];
    [self becomeFirstResponder];
    NSLog(@"magazineEndtime:%@",[[NSUserDefaults standardUserDefaults]objectForKey:EndTime]);
    if ([[NSUserDefaults standardUserDefaults]objectForKey:EndTime] && !isActivedWhenShowMenu) {
        [self getData];
    }
}
-(void)showActiveView{
    [UIView animateWithDuration:0.3 animations:^{
        CGRect rect = MainView.frame;
        rect.origin.x = -280;
        MainView.frame = rect;
        
        maskView.alpha = 0.3;
    }];
    
    if ([[NSUserDefaults standardUserDefaults]objectForKey:EndTime]) {
        isActivedWhenShowMenu = YES;
    }

    
}


- (void)getData
{
    [self showLoadingView];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSDictionary *data = [[DataRequest sharedRequest] getMagazineInfo:[_basicInfo objectForKey:@"magitemid"]];
        dispatch_async(dispatch_get_main_queue(), ^{
            if (data && [data isKindOfClass:[NSDictionary class]] && [[data objectForKey:@"result"] isKindOfClass:[NSDictionary class]]) {
                self.detailInfo = [data objectForKey:@"result"];
                [self updateDetail];
            }
        });
    });
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSDictionary *data = [[DataRequest sharedRequest] getMagazineContent:[_basicInfo objectForKey:@"magitemid"]];
        dispatch_async(dispatch_get_main_queue(), ^{
            [self removeloadingView];
            if (data && [data isKindOfClass:[NSDictionary class]] && [[data objectForKey:@"result"] isKindOfClass:[NSArray class]]) {
                self.contentArray = [data objectForKey:@"result"];
                
                [contentTableView reloadData];
                
                
                if ([[DownloadArticle shareDownloadArticle]isDownloadingWhich:[_basicInfo objectForKey:@"magitemid"]]) {
                    NSLog(@"isdownload:YES");
                    downloadBtn.hidden = YES;
                    showLabel.hidden = NO;
                    showLabel.text = @"正在下载...";
                    NSLog(@"show showlabel");
                }
                else {
                    NSArray * array = [[DataBase shareDB]selectMagaInfo];
                    NSMutableArray * downloadArray = [NSMutableArray arrayWithCapacity:0];
                    
                    for (NSDictionary * dict in array) {
                        ASIHTTPRequest * request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:[[NSString stringWithFormat:ArticleInfoURL,[[AuthorManager defaultManager] userID],[dict objectForKey:@"nc_id"]] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
                        if ([[ASIDownloadCache sharedCache] isCachedDataCurrentForRequest:request]) {
                            [downloadArray addObject:dict];
                        }
                    }
                    for (NSDictionary * dict in downloadArray) {
                        if ([[dict objectForKey:@"magitemid"]isEqualToString:[_basicInfo objectForKey:@"magitemid"]]) {
                            downloadBtn.hidden = YES;
                            downloadLabel.hidden = NO;
                            showLabel.hidden = YES;
                            NSLog(@"show downloadlabel");
                            return ;
                        }
                    }
                    NSLog(@"show downloadbutton");
                    downloadBtn.hidden = NO;
                }
            }
        });
    });
}
- (IBAction)historyButtonClicked:(id)sender {
    MagazineHistoryViewController * magaHistory = [[MagazineHistoryViewController alloc]initWithNibName:@"MagazineHistoryViewController" bundle:nil];
    magaHistory.mDict = self.basicInfo;
    [self.navigationController pushViewController:magaHistory animated:YES];
    [magaHistory release];
}

- (void)updateDetail
{
    NSString *imageStr = [_detailInfo valueForKey:@"image"];
    //        imageStr = [NSString stringWithFormat:@"%@%@",imagePreFix,imageStr];
    imageStr = [imageStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [coverImageView setImageWithURL:[NSURL URLWithString:imageStr] placeholderImage:nil];
    
    titleLabel.text = [_detailInfo valueForKey:@"magazinename"];
    sumLabel.text = [NSString stringWithFormat:@"共%d期",[[_detailInfo valueForKey:@"magazine_item_count"] intValue]];
    timeLabel.text = [_detailInfo valueForKey:@"sourcenum"];
    shareLabel.text = [NSString stringWithFormat:@"%d次",[[_detailInfo valueForKey:@"share_count"] intValue]];
    collectLabel.text = [NSString stringWithFormat:@"%d次",[[_detailInfo valueForKey:@"favorite_count"] intValue]];
    clickLabel.text = [NSString stringWithFormat:@"%d次",[[_detailInfo valueForKey:@"click_count"] intValue]];
    
    int rate = [[_detailInfo valueForKey:@"points"] intValue];
    rateLabel.text = [NSString stringWithFormat:@"%d分",rate];
    for (int i = 0; i < 5; i++) {
        UIImageView *starView = (UIImageView *)[[starsView subviews] objectAtIndex:i];
        if (i * 2 + 2 <= rate) {
            starView.image = [UIImage imageNamed:@"fullStar.png"];
        }
        else if (i * 2 + 1 <= rate) {
            starView.image = [UIImage imageNamed:@"halfStar.png"];
        }
        else {
            starView.image = [UIImage imageNamed:@"emptyStar.png"];
        }
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _contentArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MagazineContentCell *cell = (MagazineContentCell *)[tableView dequeueReusableCellWithIdentifier:@"MagazineContentCell"];
    if (cell == nil) {
        cell = [[[MagazineContentCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"MagazineContentCell"] autorelease];
    }
    cell.titleLabel.text = [NSString stringWithFormat:@"%@",[[_contentArray objectAtIndex:indexPath.row] valueForKey:@"subject"]];
    [cell setIsBookmark:[[[_contentArray objectAtIndex:indexPath.row] valueForKey:@"bookflag"] boolValue]];
    [cell adjust];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *title = [[_contentArray objectAtIndex:indexPath.row] valueForKey:@"subject"];
    CGSize size = [title sizeWithFont:[UIFont systemFontOfSize:16] constrainedToSize:CGSizeMake(280, 9999) lineBreakMode:NSLineBreakByWordWrapping];
    return 16 + size.height;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary * dict = [_contentArray objectAtIndex:indexPath.row];
    if ([[dict objectForKey:@"is_view"]intValue] == 0) {
        ABPromptView * abp = [[[ABPromptView alloc]initWithTitle:[dict objectForKey:@"state_message"]]autorelease];
        [abp show];
        [self showActiveView];
    }else{
        NSMutableArray *array = [NSMutableArray array];
        for (NSDictionary *dic in self.contentArray) {
            if ([[dic objectForKey:@"is_view"]intValue] != 0) {
                [array addObject:dic];
            }
            else {
                break;
            }
        }
        ArticleViewController *articleViewController = [[[ArticleViewController alloc] initWithNibName:@"ArticleViewController" bundle:nil] autorelease];
        articleViewController.contentArray = array;
        articleViewController.basicInfo = array[indexPath.row];
        articleViewController.currentIndex = indexPath.row;
        [self.navigationController pushViewController:articleViewController animated:YES];
    }
}

- (IBAction)navBack
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)showLoadingView
{
    if (loadingView.superview) {
        return;
    }
    if (loadingView == nil) {
        loadingView = [[[ABSpringLoadingView alloc] initWithFrame:contentTableView.frame] autorelease];
    }
    loadingView.alpha = 0;
    [self.view addSubview:loadingView];
    [UIView animateWithDuration:0.3 animations:^{
        loadingView.alpha = 1;
    }];
}

- (void)removeloadingView
{
    if (loadingView) {
        [UIView animateWithDuration:0.3 animations:^{
            loadingView.alpha = 0;
        } completion:^(BOOL finished) {
            [loadingView removeFromSuperview];
            loadingView = nil;
        }];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewDidUnload
{
    [contentTableView release];
    contentTableView = nil;
    [headerView release];
    headerView = nil;
    [coverImageView release];
    coverImageView = nil;
    [timeLabel release];
    timeLabel = nil;
    [collectLabel release];
    collectLabel = nil;
    [shareLabel release];
    shareLabel = nil;
    [clickLabel release];
    clickLabel = nil;
    [starsView release];
    starsView = nil;
    [rateLabel release];
    rateLabel = nil;
    [sumLabel release];
    sumLabel = nil;
    [titleLabel release];
    titleLabel = nil;
    [downloadLabel release];
    downloadLabel = nil;
    [downloadBtn release];
    downloadBtn = nil;
    [showLabel release];
    showLabel = nil;
    [historyButton release];
    historyButton = nil;
    [historyImage release];
    historyImage = nil;
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [_basicInfo release];
    [_detailInfo release];
    [_contentArray release];
    [contentTableView release];
    [headerView release];
    [coverImageView release];
    [timeLabel release];
    [collectLabel release];
    [shareLabel release];
    [clickLabel release];
    [starsView release];
    [rateLabel release];
    [sumLabel release];
    [titleLabel release];
    [downloadLabel release];
    [downloadBtn release];
    [showLabel release];
    [historyButton release];
    [historyImage release];
    [ActiveView release];
    [MainView release];
    [maskView release];
    [super dealloc];
}

@end
